package com.harmontronics.app.pedestal.bridge;

import android.media.MediaRecorder;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.github.piasy.rxandroidaudio.AudioRecorder;
import com.github.piasy.rxandroidaudio.PlayConfig;
import com.github.piasy.rxandroidaudio.RxAudioPlayer;
import com.harmontronics.app.pedestal.bridge.model.BaseBridge;
import com.harmontronics.app.pedestal.bridge.model.BridgeAudioResult;
import com.harmontronics.app.pedestal.bridge.model.BridgeFile;

import org.json.JSONObject;

import java.io.File;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import wendu.dsbridge.CompletionHandler;

public class AudioBridge extends BaseBridge {

    private String mFilePath =
            Utils.getApp().getFilesDir().getAbsolutePath() +
                    File.separator + "audio_record_" + System.nanoTime() + ".m4a";

    @JavascriptInterface
    public void startRecord(Object args, CompletionHandler<String> handler) {
        LogUtils.d("AUDIO.startRecord");
        if (AudioRecorder.getInstance().isStarted()) {
            handler.complete(fail("isStarted", null));
            return;
        }

        AudioRecorder.getInstance().prepareRecord(MediaRecorder.AudioSource.MIC,
                MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.AudioEncoder.AAC,
                new File(mFilePath));

        AudioRecorder.getInstance().startRecord();
        handler.complete(success("startRecord success"));
    }

    @JavascriptInterface
    public void endRecord(Object args, CompletionHandler<String> handler) {
        LogUtils.d("AUDIO.endRecord");
        if (!AudioRecorder.getInstance().isStarted()) {
            handler.complete(fail("please start record first", null));
            return;
        }

        int duration = AudioRecorder.getInstance().stopRecord();

        if (duration == -1) {
            handler.complete(fail("endRecord failed", null));
            return;
        }

        handler.complete(success(new BridgeAudioResult(mFilePath, new BridgeFile(FileUtils.getFileLength(mFilePath), mFilePath), duration)));
    }

    @JavascriptInterface
    public void play(Object argsJson, CompletionHandler<String> handler) {
        LogUtils.d("AUDIO.play");
        if (null == argsJson) {
            handler.complete(fail("参数不能为空", null));
            return;
        }

        try {
            JSONObject args = (JSONObject) argsJson;
            LogUtils.d("args: " + args.toString());
            if (!args.has("path") || TextUtils.isEmpty(args.getString("path"))) {
                handler.complete(fail("path must not be null", null));
                return;
            }

            String path = args.getString("path");
            RxAudioPlayer.getInstance().play(PlayConfig.uri(Utils.getApp(), Uri.parse(path)).looping(false).build())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Boolean>() {
                        @Override
                        public void onSubscribe(final Disposable disposable) {

                        }

                        @Override
                        public void onNext(final Boolean aBoolean) {
                            handler.complete(success("play success"));
                        }

                        @Override
                        public void onError(final Throwable throwable) {
                            handler.complete(fail(throwable.getMessage(), throwable));
                        }

                        @Override
                        public void onComplete() {
                            handler.complete(success("play completed"));
                        }
                    });
        } catch (Exception e) {
            handler.complete(fail(e.getMessage(), e));
        }

    }

    @JavascriptInterface
    public void endPlay(Object argsJson) {
        LogUtils.d("AUDIO.play");
        RxAudioPlayer.getInstance().stopPlay();
    }
}
